<script setup lang="ts">
import {ref, computed,inject} from 'vue'
import {Message} from "@arco-design/web-vue";
import {saveAs} from 'file-saver';
import {dict} from '@/api/system/dict.js';
import feeType from '@/api/finance/feeType.js';
import jsonBig from "json-bigint";
import Print from "@/utils/print";
import DataGrid from "@cps/DataGrid/DataGrid.vue";

const props = defineProps({
  visible: Boolean,
})
const config = ref({
  title: '',
  data: [],
  api: Function,
  displayDataIndex: '',
  form: {},
  ApiType: undefined,
  isDownload: undefined,
  isPrint: undefined,
})
const form = ref({})
const loading = ref({
  value: false,
  count: 0,
})
const visible = ref()
const invoicesType = inject('invoicesType','')
const data = inject('record',[])
const emit = defineEmits(['cancel'])
const options = computed(() => {
  let defaultOptions = {
    showButtons: false
  }
  return {...defaultOptions, ...config.value.form.options}
})
/*
* @param button
* @param button.title 窗口标题
* @param button.api   接口地址
* @param button.form  表单配置
* @param button.action  自定义方法,优先级高于api
* @param button.displayDataIndex  展示编号的字段,默认 shipment_no > number > name
* */
const open = async (button) => {
  if (button.action && typeof button.action === 'function') {
      button.action(props.selected)
    return;
  }
  if (!button.api || ('function' !== typeof button.api && 'function' !== typeof button.api.value)) {
    Message.error('缺少接口配置')
    return;
  }
  let api = typeof button.api === 'object' ? button.api.value : button.api
  config.value.title = 'object' === typeof button.title ? button.title.value : button.title
  config.value.displayDataIndex = button.displayDataIndex ? button.displayDataIndex : ''
  config.value.api = api
  config.value.form = button.form ? button.form : null
  config.value.ApiType = button.ApiType ? button.ApiType : null
  config.value.isDownload = button.isDownload ? button.isDownload : null
  config.value.isPrint = button.isPrint ? button.isPrint : null
  let keyIndex =  config.value.form?.id || 'id'
  form.value = button.form?.form ? JSON.parse(JSON.stringify(button.form.form)) : {}
  loading.value = {
    value: false,
    count: 0,
  }

  if (config.value.isPrint) {
    const key = config.value.form?.key || 'ids';
    let response = await config.value.api(Object.assign({[key]: props.selected}, form.value))
    if(!response.success){
      // console.log(response)
      Message.error(response.message)
      return;
    }
    content.value = response.data
  }
  visible.value = true
  buttonDisabled.value = false

  let res = await dict.getDict('currencyType')
  res.data.map(i=>{
    currency.value.push(i.title)
    currency_desc.value[i.title] = i.key
  })
  currency.value = []
  // currency_desc.value = []
  res = await feeType.list({})
  res.data.map(i=>{
    fee_type.value.push(i.fee_name)
    fee_type_desc.value[i.fee_name] = i.id
  })
  fee_type.value = []
  // fee_type_desc.value = []
  userData.value = [
    {
      business_at: getCurrentDate(),
      fee_type_desc: '',
      currency_desc: '人民币',
      unit_desc: 'KG',
      unit_amount: '',
      memo: '',
      remark: '',
    }
  ]
}

const getCurrentDate = ()=> {
    if(invoicesType.value == 'shipment'){
      return data.value.picking_at
    }else{
      const now = new Date();
      const year = now.getFullYear();
      // 注意：JavaScript的月份是从0开始的，所以需要加1
      const month = String(now.getMonth() + 1).padStart(2, '0');
      // 注意：JavaScript的日期也是从1开始的，所以不需要额外处理
      const date = String(now.getDate()).padStart(2, '0');
      const hours = String(now.getHours()).padStart(2, '0');
      const minutes = String(now.getMinutes()).padStart(2, '0');
      const seconds = String(now.getSeconds()).padStart(2, '0');
      return `${year}-${month}-${date} ${hours}:${minutes}:${seconds}`;
    }
}

const cancel = () => {
  form.value = {}
  config.value.form = {}
  visible.value = false
}
defineExpose({
  open,
})
const content = ref([])
const buttonDisabled = ref(false)
const submitApi = async ()=>{
  let feeList = userData.value.filter(j=>{
      return j.business_at || j.fee_type_desc || j.currency_desc || j.unit_desc || j.unit_amount || j.unit || j.memo || j.remark
    })
  for(let i = 0 ; i < feeList.length; i++){
    //  if(!feeList[i].business_at){
    //       Message.error('业务时间必填')
    //       return;
    //  }
     if(!feeList[i].fee_type_desc){
          Message.error('费用类型必填')
          return;
     }
     if(!feeList[i].currency_desc){
          Message.error('币种必填')
          return;
     }
     if(!feeList[i].unit_desc){
          Message.error('单位必填')
          return;
     }
     if(!feeList[i].unit_amount){
          Message.error('单位费用必填')
          return;
     }
     feeList[i].invoices_type = invoicesType.value
  }
  buttonDisabled.value = true
  feeList.map(j=>{
      j = descToId(fee_type_desc.value,'fee_type',j)
      j = descToId(currency_desc.value,'currency',j)
      j = descToId(unit_desc.value,'unit',j)
  })

    let item = data.value
    setTimeout(() => {
      buttonDisabled.value = false
    }, 2000);
    console.log(item)
    let res = await config.value.api(item.id,{fees:feeList})
    if(res.success === false){
      Message.error(res.message)
      return;
    }
    Message.success(res.message)
    config.value.form.submited()
    visible.value = false
    
}
const descToId = (list,key,data)=>{
  for(let k in list){
    if(k == data[key+'_desc']){
          data[key] = list[k]
      }
  }
  return data
}

const fee_type = ref([])
const fee_type_desc = ref({})
const currency = ref([])
const currency_desc = ref({})
const unit = ref(['KG','m³','票','箱'])
const unit_desc = ref({
  'KG':'1',
  'm³':'2',
  '票':'3',
  '箱':'4',
})

const userData = ref([])

const columns = ref([
  {title: '业务时间', data: 'business_at',type: 'date', dateFormat: 'YYYY-MM-DD HH:mm:ss'},
  {title: '费用类型', data: 'fee_type_desc',required:true,
    type: 'dropdown',
    source: fee_type.value
  },
  {title: '币种', data: 'currency_desc',required:true,
    type: 'dropdown',
    source: currency.value
  },
  {title: '汇率', data: 'unit'},
  {title: '单位', data: 'unit_desc',required:true,
    type: 'dropdown',
    source: unit.value
  },
  {title: '单位费用', data: 'unit_amount',required:true,type:'numeric'},
  {title: '描述', data: 'memo'},
  {title: '备注', data: 'remark'},
])
</script>

<template>
  <a-modal :title="config.title" :visible='visible' @cancel="cancel" width="60%"
           unmount-on-close
           :hide-cancel="loading.count > 0"
           >
    <p v-if="!config.form">注：不填写业务时间则根据偏好设置的流水业务时间来生成流水</p>
    <!-- todo 成功批量反馈增加结果下载    -->
    <div class="h-96 overflow-y-auto" v-if="!config.isDownload && !config.isPrint">
      <data-grid :columns="columns" v-model="userData"/>
    </div>
    <template #footer>
      <a-button v-if="!buttonDisabled" type="primary" @click="submitApi()">提交</a-button>
      <a-button @click="visible=false">{{ buttonDisabled ? '关闭' : '取消'}}</a-button>
    </template>
  </a-modal>
</template>

<style scoped>
@media print {
  .print-break{
    break-after: page;
  }
}
</style>